package array.nsum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FourSum {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            List<List<Integer>> triples = threeSum(nums, i + 1, target - nums[i]);
            for (List<Integer> triple : triples) {
                triple.add(nums[i]);
                res.add(triple);
            }
            while (i < n - 1 && nums[i] == nums[i + 1]) i++;
        }
        return res;
    }

    private List<List<Integer>> threeSum(int[] nums, int i, int target) {
        List<List<Integer>> res = new ArrayList<>();
        for (int j = i; j < nums.length; j++) {
            List<List<Integer>> tuples = twoSum(nums, j + 1, target - nums[j]);
            for (List<Integer> tuple : tuples) {
                tuple.add(nums[j]);
                res.add(tuple);
            }
            // 跳过第一个数字
            while (j < nums.length - 1 && nums[j] == nums[j + 1]) j++;
        }
        return res;
    }

    private List<List<Integer>> twoSum(int[] nums, int i, int target) {
        int lo = i, hi = nums.length - 1;
        List<List<Integer>> res = new ArrayList<>();
        while (lo < hi) {
            int sum = nums[lo] + nums[hi];
            int left = nums[lo], right = nums[hi];
            if (sum < target) {
                while (lo < hi && nums[lo] == left)
                    lo++;
            } else if (sum > target) {
                while (lo < hi && nums[hi] == right)
                    hi--;
            } else {
                res.add(Arrays.asList(nums[lo], nums[hi]));
                while (lo < hi && nums[lo] == left)
                    lo++;
                while (lo < hi && nums[hi] == right)
                    hi--;
            }
        }
        return res;
    }
}
